package com.masterclient.app.modules.shop.adapter;

import android.app.Activity;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.LayoutHelper;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.bumptech.glide.load.Transformation;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.eoner.commonbean.product.CommodityOversea;
import com.eoner.commonbean.product.ProductMessage;
import com.eoner.commonbean.product.ProductTag;
import com.eoner.baselibrary.utils.ScreenUtils;
import com.eoner.baselibrary.utils.Utils;
import com.eoner.baselibrary.utils.ViewTransformUtil;
import com.eoner.managerlibrary.router.AroutePath;
import com.masterclient.app.R;
import com.masterclient.app.base.MainViewHolder;
import com.masterclient.app.widget.TagTextView;

import java.util.List;

import jp.wasabeef.glide.transformations.CropCircleWithBorderTransformation;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;

/**
 * @auther hjian
 * @date 2020/4/9.
 */
public class ProductsLayoutAdapter extends DelegateAdapter.Adapter<MainViewHolder> {

    private Activity mContext;
    private List<LayoutHelper> mLayoutHelper;
    private VirtualLayoutManager.LayoutParams mLayoutParams;
    private List<ProductMessage> data;
    private boolean isStaggered = true;
    private int width;

    public List<ProductMessage> getData() {
        return data;
    }

    public void setItemType(boolean isStaggered) {
        this.isStaggered = isStaggered;
//        notifyDataSetChanged();
//        notifyItemRangeChanged(0,data.size());
    }


    private String[] strings;
    /*
     **source_page
     */
    public void setStrings(String... strings) {
        this.strings = strings;
    }

    public ProductsLayoutAdapter(Activity context, List<LayoutHelper> layoutHelper, @NonNull VirtualLayoutManager.LayoutParams layoutParams, List<ProductMessage> data) {
        this.mContext = context;
        this.mLayoutHelper = layoutHelper;
        this.mLayoutParams = layoutParams;
        this.data = data;
        this.strings = new String[]{};
        width = (int) ((ScreenUtils.getScreenWidth() - ScreenUtils.dp2px(41)) / 2f);
    }

    @Override
    public LayoutHelper onCreateLayoutHelper() {
        return mLayoutHelper.get(isStaggered ? 0 : 1);
    }

    @NonNull
    @Override
    public MainViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new MainViewHolder(LayoutInflater.from(mContext).inflate(viewType == 5 ?
                R.layout.item_search_good_staggered : R.layout.item_search_good_list, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull MainViewHolder holder, int position) {
        if (mLayoutParams != null) {
            holder.itemView.setLayoutParams(
                    new VirtualLayoutManager.LayoutParams(mLayoutParams));
        }

        ProductMessage item = data.get(position);
        String country = "", country_logo = "", country_tag = "";
        CommodityOversea oversea = item.getOversea();
        if (oversea != null) {
            country = oversea.getCountry_name();
            country_logo = oversea.getCountry_logo();
            country_tag = oversea.getTag();
        }
        ImageView imageView = holder.itemView.findViewById(R.id.iv_goods);
        if (isStaggered) {
            ((TextView) holder.itemView.findViewById(R.id.tv_title)).setText(item.getTitle());
            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) imageView.getLayoutParams();
            layoutParams.height = width;
            layoutParams.width = width;

            ViewTransformUtil.glideImageView(mContext, item.getImage(), imageView, new Transformation[]{
                    new RoundedCornersTransformation(ScreenUtils.dp2px(7), 0,
                            RoundedCornersTransformation.CornerType.TOP)}, R.mipmap.defaults);

            ImageView storeIcon = holder.itemView.findViewById(R.id.iv_store);
            storeIcon.setVisibility(TextUtils.isEmpty(item.getShop_icon()) ? View.GONE : View.VISIBLE);
            ViewTransformUtil.glideImageView(mContext, item.getShop_icon(), storeIcon, new Transformation[]{new CenterCrop()}, R.mipmap.defaults_1);

            holder.itemView.findViewById(R.id.overseas_direct_mail_ll).setVisibility(!TextUtils.isEmpty(country) ? View.VISIBLE : View.GONE);
            ((TextView) holder.itemView.findViewById(R.id.overseas_direct_mail_name)).setText(!TextUtils.isEmpty(country) ? country : "");
            ViewTransformUtil.glideImageView(mContext, country_logo, ((ImageView) holder.itemView.findViewById(R.id.overseas_direct_mail_icon)),
                    new CropCircleWithBorderTransformation(0, mContext.getResources().getColor(R.color.white)), R.mipmap.defaults);
            ((TextView) holder.itemView.findViewById(R.id.overseas_direct_mail_name)).setMaxEms(!TextUtils.isEmpty(country_tag) && "2".equals(country_tag) ? 4 : 20);
        } else {
            TagTextView tvTitle = holder.itemView.findViewById(R.id.tv_title);
            if (TextUtils.isEmpty(country) && TextUtils.isEmpty(item.getShop_icon())) {
                tvTitle.setText(item.getTitle());
            } else {
                tvTitle.setContentAndImgTag(" " + item.getTitle(),country,country_logo,country_tag,item.getShop_icon());
            }
            tvTitle.setMaxLines(2);
            tvTitle.setEllipsize(TextUtils.TruncateAt.END);
            ViewTransformUtil.glideImageView(mContext, item.getImage(), imageView,
                    new Transformation[]{new CenterCrop(), new RoundedCornersTransformation(
                            ScreenUtils.dp2px(7), 0)}, R.mipmap.defaults);
        }

        TextView tvDayTxt = holder.itemView.findViewById(R.id.tv_day_txt);
        TextView tvDayPrice = holder.itemView.findViewById(R.id.tv_day_price);
        TextView tvOfficialTxt = holder.itemView.findViewById(R.id.tv_official_txt);
        TextView tvOfficialPrice = holder.itemView.findViewById(R.id.tv_official_price);
        TextView tv_coin_deduct = holder.itemView.findViewById(R.id.tv_coin_deduct);
        TextView tv_activity_tag = holder.itemView.findViewById(R.id.tv_activity_tag);

        //活动文案
        if (item.getPriceTagBean() != null && !TextUtils.isEmpty(item.getPriceTagBean().getActivity_price_tag())) {
            tv_activity_tag.setText(item.getPriceTagBean().getActivity_price_tag());
            tv_activity_tag.setVisibility(View.VISIBLE);
        } else {
            tv_activity_tag.setVisibility(View.GONE);
        }

        //日常价
        if (item.getPriceTagBean() != null && !TextUtils.isEmpty(item.getPriceTagBean().getBase_price_tag())) {
            tvDayTxt.setText(item.getPriceTagBean().getBase_price_tag());
            if (!TextUtils.isEmpty(item.getDaily_price())) {
                tvDayPrice.setText("¥" + item.getDaily_price());
                tvDayPrice.setVisibility(View.VISIBLE);
            }
            tvDayTxt.setVisibility(View.VISIBLE);
        } else {
            tvDayTxt.setVisibility(View.GONE);
            tvDayPrice.setVisibility(View.GONE);
        }

        //官方价
        if (item.getPriceTagBean() != null && !TextUtils.isEmpty(item.getPriceTagBean().getMarket_price_tag())) {
            tvOfficialTxt.setText(item.getPriceTagBean().getMarket_price_tag());
            if (!TextUtils.isEmpty(item.getMarket_price())) {
                tvOfficialPrice.setText("¥" + item.getMarket_price());
                tvOfficialPrice.setPaintFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
                tvOfficialPrice.setVisibility(View.VISIBLE);
            }
            tvOfficialTxt.setVisibility(View.VISIBLE);
        } else {
            tvOfficialTxt.setVisibility(View.GONE);
            tvOfficialPrice.setVisibility(View.GONE);
        }


//            TextView newcomer = holder.itemView.findViewById(R.id.newcomer_price);
        TextView tvActivityMj = holder.itemView.findViewById(R.id.tv_activity_mj);
        TextView buy_giveaway = holder.itemView.findViewById(R.id.buy_giveaway);
        if (item.getTags() != null && item.getTags().size() > 0) {
            List<ProductTag> tags = item.getTags();
            String new_member_tag = "";//新人标签
            String present_tag = "";//赠品标签
            String activity_mj_tag = "";//满减标签
            String deduction_rate_tag = "";//金币抵扣
            for (ProductTag tag : tags) {
                if ("2".equals(tag.getType())) {
                    new_member_tag = tag.getName();
                } else if ("3".equals(tag.getType())) {
                    activity_mj_tag = tag.getName();
                } else if ("4".equals(tag.getType())) {
                    present_tag = tag.getName();
                } else if("5".equals(tag.getType())){
                    deduction_rate_tag = tag.getName();
                }
            }

            //金币抵扣
            if (!TextUtils.isEmpty(deduction_rate_tag)){
                tv_coin_deduct.setText(deduction_rate_tag);
                tv_coin_deduct.setVisibility(View.VISIBLE);
            }else {
                tv_coin_deduct.setVisibility(View.GONE);
            }

            if (isStaggered){
                if (!TextUtils.isEmpty(present_tag) && item.getPriceTagBean() != null && !TextUtils.isEmpty(item.getPriceTagBean().getDeduction_rate_tag())
                        && !TextUtils.isEmpty(activity_mj_tag)){
                    buy_giveaway.setVisibility(View.GONE);
                } else {
                    buy_giveaway.setVisibility(!TextUtils.isEmpty(present_tag)?View.VISIBLE:View.GONE);
                    buy_giveaway.setText(TextUtils.isEmpty(present_tag)?"":present_tag);
                }
            }else {
                buy_giveaway.setVisibility(!TextUtils.isEmpty(present_tag)?View.VISIBLE:View.GONE);
                buy_giveaway.setText(TextUtils.isEmpty(present_tag)?"":present_tag);
            }

            if (!TextUtils.isEmpty(activity_mj_tag)) {
                tvActivityMj.setVisibility(View.VISIBLE);
                tvActivityMj.setText(activity_mj_tag);
            } else {
                tvActivityMj.setVisibility(View.GONE);
            }

//                if (!TextUtils.isEmpty(new_member_tag)) {
//                    newcomer.setVisibility(View.VISIBLE);
//                    newcomer.setText(new_member_tag);
//                    if (item.getFresh_user() != null) {
//                        ((TextView) holder.itemView.findViewById(R.id.tv_price_now)).setText(item.getFresh_user().getPrice());
//                    }
//                } else {
//                    newcomer.setVisibility(View.GONE);
//                }
        }else {
            tv_coin_deduct.setVisibility(View.GONE);
            tvActivityMj.setVisibility(View.GONE);
            buy_giveaway.setVisibility(View.GONE);
        }

        ImageView ivTagNew = holder.itemView.findViewById(R.id.iv_tag_new);
        //新品上架
        if (item.isIs_new()) {
            ivTagNew.setVisibility(View.VISIBLE);
        } else {
            ivTagNew.setVisibility(View.GONE);
        }

        View ivShouqing = holder.itemView.findViewById(R.id.ll_shouqing);

        if (!TextUtils.isEmpty(item.getStock())) {
            if (Long.valueOf(item.getStock()) <= 0) {
                ivShouqing.setVisibility(View.VISIBLE);
            } else {
                ivShouqing.setVisibility(View.GONE);
            }
        }

        View rl_video = holder.itemView.findViewById(R.id.rl_video);
        if (item.isHas_video()) {
            rl_video.setVisibility(View.VISIBLE);
        } else {
            rl_video.setVisibility(View.GONE);
        }
        TextView tv_bofang = holder.itemView.findViewById(R.id.tv_bofang);
        tv_bofang.setTypeface(Typeface.createFromAsset(mContext.getAssets(), "fonts/iconfont.ttf"));
//        ((TextView) holder.itemView.findViewById(R.id.tv_sub_title)).setText(item.getSub_title());

        //显示价
        TextView tv_price_unit = holder.itemView.findViewById(R.id.tv_price_unit);
        TextView tv_price_now = holder.itemView.findViewById(R.id.tv_price_now);
        if("2".equals(item.getProduct_type())){
            //helper.setText(R.id.tv_price_now,item.getIntegral_price() + "金币");
            tv_price_unit.setVisibility(View.GONE);
            Utils.set_goodsdetail_goldprice_style(tv_price_now, item.getIntegral_price());
        }else{
            tv_price_now.setText(item.getPrice());
            tv_price_unit.setVisibility(View.VISIBLE);
        }
        Utils.setDin(tv_price_now,mContext);
        Utils.setDin(tv_price_unit,mContext);

        //佣金显示
        TextView tv_money_earn = holder.itemView.findViewById(R.id.tv_money_earn);
        LinearLayout ll_double_earn = holder.itemView.findViewById(R.id.ll_double_earn);
        if (TextUtils.isEmpty(item.getCommission()) || 0 == Double.valueOf(item.getCommission())) {
            tv_money_earn.setVisibility(View.GONE);
            ll_double_earn.setVisibility(View.GONE);
        } else {
            tv_money_earn.setVisibility(View.VISIBLE);
            tv_money_earn.setText("赚" + item.getCommission());
            TextView tv_double_earn = holder.itemView.findViewById(R.id.tv_double_earn);
            if (!TextUtils.isEmpty(item.getDouble_commission()) &&
                    Float.parseFloat(item.getDouble_commission()) > 0) {
                tv_money_earn.setVisibility(View.GONE);
                ll_double_earn.setVisibility(View.VISIBLE);
                tv_double_earn.setText("赚" + item.getDouble_commission());
            } else {
                ll_double_earn.setVisibility(View.GONE);
            }
        }

        //会员价
        TextView tagPriceVip = holder.itemView.findViewById(R.id.tag_vip_price);
        TextView tvPriceVip = holder.itemView.findViewById(R.id.tv_vip_price);
        if (item.isShow_vip_price()){
            tagPriceVip.setVisibility(View.VISIBLE);
            tvPriceVip.setVisibility(View.VISIBLE);
            tvPriceVip.setText("¥"+item.getVip_price());
            tvDayTxt.setVisibility(View.GONE);
            tvDayPrice.setVisibility(View.GONE);
            tvOfficialTxt.setVisibility(View.GONE);
            tvOfficialPrice.setVisibility(View.GONE);
        }else {
            tagPriceVip.setVisibility(View.GONE);
            tvPriceVip.setVisibility(View.GONE);
        }

        //商品图片上的图标
        ImageView ivActivity = holder.itemView.findViewById(R.id.iv_activity);
        double ratio = 1;
        if (!TextUtils.isEmpty(item.getImage_width())){
            if (isStaggered) {
                ratio = width/Double.parseDouble(item.getImage_width());
            }else {
                ratio = ScreenUtils.dp2px(107)/Double.parseDouble(item.getImage_width());
            }
        }
        if(item.getIconInfo()!=null
                && !TextUtils.isEmpty(item.getIconInfo().iconHeight)
                &&!TextUtils.isEmpty(item.getIconInfo().iconWidth)) {
            int leftMargin = (int) (Integer.parseInt(item.getIconInfo().iconLeftMargin)*ratio);
            int topMargin = (int) (Integer.parseInt(item.getIconInfo().iconTopMargin)*ratio);
            int bottomMargin = (int) (Integer.parseInt(item.getIconInfo().iconBottomMargin)*ratio);
            ViewTransformUtil.glideImageView(mContext,item.getIconInfo().iconImage,ivActivity,R.mipmap.defaults);
            ivActivity.setVisibility(View.VISIBLE);
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) ivActivity.getLayoutParams();
            params.height = (int) (Integer.valueOf(item.getIconInfo().iconHeight)*ratio);
            params.width = (int) (Integer.valueOf(item.getIconInfo().iconWidth)*ratio);
            params.addRule(RelativeLayout.ALIGN_BOTTOM,0);
            params.addRule(RelativeLayout.ALIGN_PARENT_LEFT,0);
            params.setMargins(0, 0, 0, 0);
            switch (item.getIconInfo().iconMarginType) {
                case "1":
                    params.addRule(RelativeLayout.ALIGN_BOTTOM,R.id.iv_goods);
                    params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
                    params.setMargins(leftMargin, topMargin, 0, bottomMargin);
                    break;
                case "2":
                    params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
                    params.setMargins(leftMargin, topMargin, 0, bottomMargin);
                    break;
            }
            ivActivity.setLayoutParams(params);
        }else {
            ivActivity.setVisibility(View.GONE);
        }

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ARouter.getInstance().build(AroutePath.COMMODITY_DETAIL_ACTIVITY)
                        .withString("id", item.getProduct_id())
                        .withString("source_position", position+"")
                        .withString("source_page",strings.length>0?strings[0]:"")
                        .navigation();
            }
        });
    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    @Override
    public int getItemViewType(int position) {
        return isStaggered ? 5 : 6;
    }

    public void addData(List<ProductMessage> shProducts, boolean isRefresh) {
        if (isRefresh) {
            data = shProducts;
            notifyDataSetChanged();
        } else {
            data.addAll(shProducts);
            notifyItemRangeInserted(data.size() - shProducts.size(), shProducts.size());
        }
    }
}
